package model.client.responsehandler;

import model.entity.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import javafx.application.Platform;
import model.util.ChannelUtils;
import view.ChatInterface;

/**
 * @Description 接受普通聊天消息并将内容打印到聊天框
 * @author 14548
 */
public class ClientChatMessageHandler extends SimpleChannelInboundHandler<Message> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        AttributeKey<String> name = AttributeKey.valueOf("name");
        String userName = ctx.channel().attr(name).get();
//        System.out.println("Attribute:"+userName);
        String interfaceId = msg.getInterfaceId();

        ChatInterface chatInterface = ChannelUtils.getChatInterface(interfaceId);

        int jud;
        if(msg.getId().equals(userName)) {
            jud = 1;
        }else {
            jud = 0;
        }

        Platform.runLater(new Runnable() {
            @Override
            public void run() {

                chatInterface.sendMessageToChatBoxListView(msg.getId(), msg.getMsg(), jud);
            }
        });

        String info = msg.getMsg();
        System.out.println(msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
    }
}
